package com.yuexunit.mobilenurse.module.PutAdvice.ui;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.joyree.JoyreeScannerInterface;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.titlebar.TitleBar_DocAdvice;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Injection;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXExecuteOrder;
import com.yuexunit.mobilenurse.module.PatientDetail.ui.Act_PatientDetail_Normal;
import com.yuexunit.mobilenurse.module.PutAdvice.adapter.PutAdapter;
import com.yuexunit.mobilenurse.module.PutAdvice.model.impl.PutModel;
import com.yuexunit.mobilenurse.module.PutAdvice.presenter.IPutPrensenter;
import com.yuexunit.mobilenurse.module.PutAdvice.presenter.impl.PutPrensenter;
import com.yuexunit.mobilenurse.module.PutAdvice.ui.view.IPutView;
import com.yuexunit.mobilenurse.widget.Dialog_Fail;
import com.yuexunit.mobilenurse.widget.Dialog_Pass;
import com.yuexunit.mobilenurse.widget.Dialog_Success;
import com.yuexunit.mobilenurse.widget.EmptyLayout;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/18 0018.
 */

public class Act_Put extends KJActivity implements IPutView {
    @Bind(R.id.empty_layout)
    public EmptyLayout mEmptyLayout;
    @Bind(R.id.injection_list)
    public ListView injection_list;
    @Bind(R.id.title)
    TextView title;

    private BaseAdapter adapter;
    IPutPrensenter presenter;
    private String visitno;
    LoadingDialog loadingDialog;

    //定时器时间
    int countTime = 3;

    Dialog_Fail.Builder builder_fail;
    Dialog_Success.Builder builder_success;

    Handler handler_noid;
    Timer time;
    TimerTask timetask;

    public static final int SHOW_DIALOG = 1;
    public static final int DISMISS_DIALOG = -1;

    ArrayList<DocAdvice_Injection> docAdvice_all = new ArrayList<DocAdvice_Injection>();

    //来源
    boolean source;
    //位置
    private int position;
    //医嘱标识条码
    private String barcode;

    String type = "";

    //巨力
    private IntentFilter mBarcodeFilter = null;
    public static final String BARCODE_DATA_ACTION = "android.intent.action.BARCODEDATA";
    public static final String BARCODE_RESULT = "barcode_result";
    public JoyreeScannerInterface mScanner = null;

    //杭州凯立
    private BroadcastReceiver mBrReceiver;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_chemical);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("source");
        presenter = new PutPrensenter(this, new PutModel());
        title.setText("摆药");
        if (type.equals("2")) {
            visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
            if (SystemTool.checkNet(aty)) {
                this.dialogState(SHOW_DIALOG);
                presenter.showInjectionList(visitno);
            } else {
                ViewInject.toast("网络异常，请检查网络是否连接!");
            }
        } else if (type.equals("1")) {
            mEmptyLayout.dismiss();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Register_Receiver();
        Register_Receiver_Joyeer();
        getsystemscandata();
        if(AppConfig.NURSEID.equals(""))
        {
            AppConfig.NURSEID = PreferenceHelper.readString(aty,AppConfig.NURSE_INFO,AppConfig.NURSE_LOGID);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        try {
            unregisterReceiver(PatientDetailReceiver);
        } catch (IllegalArgumentException e) {

        }

        try {
            unregisterReceiver(mBarcodeReceiver);
        } catch (IllegalArgumentException e) {

        }

        try {
            unregisterReceiver(mBrReceiver);
        } catch (IllegalArgumentException e) {

        }

        mScanner = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(PatientDetailReceiver);
        } catch (IllegalArgumentException e) {

        }

        try {
            unregisterReceiver(mBarcodeReceiver);
        } catch (IllegalArgumentException e) {

        }

        try {
            unregisterReceiver(mBrReceiver);
        } catch (IllegalArgumentException e) {

        }

        mScanner = null;
    }

    @Override
    @OnClick({R.id.bloodcollection_img_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bloodcollection_img_back:
                finish();
                break;
        }
    }

    @Override
    public void dialogState(int status) {
        switch (status) {
            case SHOW_DIALOG:
                loadingDialog = new LoadingDialog(this);
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                break;
            case DISMISS_DIALOG:
                loadingDialog.dismiss();
                break;
        }
    }

    @Override
    public void showInjectionList(ArrayList<DocAdvice_Injection> list) {
        docAdvice_all = list;
        adapter = new PutAdapter(this, aty, docAdvice_all);
        injection_list.setAdapter(adapter);
        mEmptyLayout.dismiss();
        if (loadingDialog.isShowing()) {
            dialogState(DISMISS_DIALOG);
        }
    }

    @Override
    public void execDialog(int status, String message) {
        switch (status) {
            case AppConfig.EXEC_DIALOG_UNPASS_INNER:
                show_unpass(message);
                loadingDialog.dismiss();
                break;
            case AppConfig.EXEC_DIALOG_PASS_INNER:
                show_pass();
                loadingDialog.dismiss();
                break;

        }
    }

    @Override
    public void getExecData(YXExecuteOrder executeOrderData) {

    }

    public void ExecuteOrder_inner(final Boolean source, final String barcode, int position) {
        this.source = source;
        this.barcode = barcode;
        this.position = position;
        showExecDialog();
    }


    public void show_pass() {
        final Dialog_Pass.Builder dialog_pass = new Dialog_Pass.Builder(aty);
        dialog_pass.setMessage("摆药成功");
        dialog_pass.create().show();
        handler_noid = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    Log.v("time", msg.what + "");
                } else {
                    countTime = 3;
                    if (time != null) {
                        time.cancel();
                        time = null;
                    }

                    if (timetask != null) {
                        timetask.cancel();
                        timetask = null;
                    }
                    dialog_pass.dismiss();
                    if (type.equals("2")) {
                        dialogState(SHOW_DIALOG);
                        presenter.showInjectionList(visitno);
                    }
                }
                super.handleMessage(msg);
            }

        };

        time = new Timer(true);
        timetask = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler_noid.sendMessage(msg);

            }

        };
        time.schedule(timetask, 0, 1000);
    }

    public void show_unpass(String message) {
        builder_fail = new Dialog_Fail.Builder(aty);
        builder_fail.setMessage(message);
        builder_fail.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder_fail.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_fail.create().show();
    }

    public void showExecDialog() {
        builder_success = new Dialog_Success.Builder(aty);
        builder_success.setMessage("确认摆药?");
        builder_success.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadingDialog = new LoadingDialog(aty);
                        loadingDialog.setCanceledOnTouchOutside(false);
                        loadingDialog.show();
                        presenter.Execorder(true, "", barcode, AppConfig.NURSEID);
                    }
                });

        builder_success.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_success.create().show();
    }


    //注册条码Receiver
    private void Register_Receiver() {
        //注册条码Receiver
        IntentFilter scanDataIntentFilter = new IntentFilter();
        scanDataIntentFilter.addAction("com.android.scancontext");
        scanDataIntentFilter.addAction("com.android.scanservice.scancontext");
        registerReceiver(PatientDetailReceiver, scanDataIntentFilter);

        if (!isServiceRunning("com.android.scanservice.ScanService")) {
//            ViewInject.toast("未检测到扫描服务");
        }
    }

    //条码Receiver
    private BroadcastReceiver PatientDetailReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int keycode = intent.getIntExtra("Scan_Keycode", 0);
            if (action.equals("com.android.scanservice.scancontext")) {
                String result = intent.getStringExtra("Scan_context");
                String type = intent.getStringExtra("Scan_type");
                if (!result.equals("")) {
                    String type_tag = result.substring(0, 1);
                    if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))
                            && type_tag.equals("2")) {
                        loadingDialog = new LoadingDialog(aty);
                        loadingDialog.setCanceledOnTouchOutside(false);
                        loadingDialog.show();
                        presenter.Execorder(true, "", result, AppConfig.NURSEID);
                    } else {
                        Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };

    // 检查Service是否运行
    private boolean isServiceRunning(String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(100);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    //巨力
    private void Register_Receiver_Joyeer() {
        mScanner = new JoyreeScannerInterface(getApplication());
        mScanner.enableBeep(true);
        mScanner.enableVibrate(true);
        mScanner.setOutputMode(0);

        mBarcodeFilter = new IntentFilter();
        mBarcodeFilter.addAction(BARCODE_DATA_ACTION);

        registerReceiver(mBarcodeReceiver, mBarcodeFilter);
    }


    private BroadcastReceiver mBarcodeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            if (intent != null && intent.getStringExtra(BARCODE_RESULT) != null) {
                String result = intent.getStringExtra(BARCODE_RESULT);
                if (!result.equals("")) {
                    String type_tag = result.substring(0, 1);
                    if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))
                            && type_tag.equals("2")) {
                        loadingDialog = new LoadingDialog(aty);
                        loadingDialog.setCanceledOnTouchOutside(false);
                        loadingDialog.show();
                        presenter.Execorder(true, "", result, AppConfig.NURSEID);
                    } else {
                        Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

    };

    public void getsystemscandata() {
        final String getstr = "com.android.receive_scan_action";
        mBrReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(getstr)) {
                    String result = intent.getStringExtra("data");
                    if (!result.equals("")) {
                        String type_tag = result.substring(0, 1);
                        if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))
                                && type_tag.equals("2")) {
                            loadingDialog = new LoadingDialog(aty);
                            loadingDialog.setCanceledOnTouchOutside(false);
                            loadingDialog.show();
                            presenter.Execorder(true, "", result, AppConfig.NURSEID);
                        } else {
                            Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter(getstr);
        registerReceiver(mBrReceiver, filter);
    }
}
